package io.renren.modules.posinfo.service.impl;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import io.renren.modules.labelhistory.entity.LabelhistoryinfoEntity;
import io.renren.modules.labonin.entity.LableonlineinfoEntity;
import io.renren.modules.norminfo.entity.NorminfoEntity;
import io.renren.modules.posinfo.controller.PosSocketHandler;
import io.renren.modules.posinfo.entity.Utype1Entity;
import io.renren.modules.posinfo.entity.Utype2Entity;
import io.renren.modules.welderinfo.service.impl.WelderinfoServiceImpl;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.net.URI;
import java.net.URISyntaxException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;

import io.renren.modules.posinfo.dao.PosinfoDao;
import io.renren.modules.posinfo.entity.PosinfoEntity;
import io.renren.modules.posinfo.service.PosinfoService;
import org.springframework.web.client.RestTemplate;

//import javax.xml.transform.Result;
//import javax.xml.ws.Response;

@Slf4j
@Service("posinfoService")
public class PosinfoServiceImpl extends ServiceImpl<PosinfoDao, PosinfoEntity> implements PosinfoService {
    @Autowired
    PosinfoDao posinfoDao;
    @Autowired
    PosSocketHandler posSocketHandler;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PosinfoEntity> page = this.page(
                new Query<PosinfoEntity>().getPage(params),
                new QueryWrapper<PosinfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<PosinfoEntity> getPosInfo(String mid) {
        return posinfoDao.getPosInfo(mid);
    }

    @Data
    public static class  ReHeader{
        private String username;
        private String password;
        private String http_api_version;
    }
    @Data
    public class JsonObject {
        public int type;
        public String message;
        public List<ResultObject> result;
    }
    @Data
    public class ResultObject {
        public int card_id;
        public double x;
        public double y;
        public double z;
        public int card_relative_z;
        public long time;
        public int floor_id;
        public int uuid;
        public int utype;
        @JsonProperty("static")
        public int isStatic;
        public int zigbee;
        public int pos_data_type;
        public int on_line;
        public int id;
        public String floor_name;
        public int building_id;
        public String building_name;
        public int scene_id;
        public String scene_name;
        public String person_name;
        public int branch_id;
        public String unit;
        public String visitor_name;
        public String branch_name;
        public String licence;
    }
    //    @Scheduled(cron = "0/5 * * * * ?")
    public Object getPosToken() throws JsonProcessingException {
        RestTemplate restTemplate = new RestTemplate();

        // 获取token
//        UsersServiceImpl.ReHeader reHeader = new UsersServiceImpl.ReHeader();
        PosinfoServiceImpl.ReHeader reHeader = new PosinfoServiceImpl.ReHeader();
        reHeader.setUsername("TestUWB");
        reHeader.setPassword("aff8c7c4f8d9fab3bb7322ea79cc5170");
        reHeader.setHttp_api_version("4.12.2");
//        String url = "http://10.142.3.128/EHCommon/admin/user/login";
        String url = "https://pfclocation.cmhijs.cn/EHCommon/admin/user/login";
        String result = restTemplate.postForObject(url,reHeader, String.class);
//       System.out.println(result);
//        System.out.println("----------------");
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode = objectMapper.readTree(result);
        String token = String.valueOf(jsonNode.get("result").get("Authorization")).replace("\"","");

        return token.toString();
    }
    //2.获取所有定位信息
//    @Async("screenTaskExecutor")
    //创建一个全局Map，用来存放cardid和对应的iswork
    Map<Integer,Integer> previousIsWorkMap = new HashMap<>();
    @Scheduled(cron = "0/3 * * * * ?")
    public String getPosInfo() throws InterruptedException, JsonProcessingException, URISyntaxException {
//        String url = "http://10.142.3.128/EHCommon/realtime/realTime/getAllCardNowPos";
        String url = "https://pfclocation.cmhijs.cn/EHCommon/realtime/realTime/getAllCardNowPos";
        String token=getPosToken().toString();
        ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
        RestTemplate restTemplate = new RestTemplate(requestFactory);

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.set("Authorization",token);
//        httpHeaders.setBearerAuth(token);
        RequestEntity<Void> requestEntity = new RequestEntity<>(httpHeaders, HttpMethod.GET,new URI(url));
        ResponseEntity<String> responseEntity = restTemplate.exchange(requestEntity, String.class);
        String allposinfo = responseEntity.getBody();
//        System.out.println("所有定位信息");
//        System.out.println(allposinfo);
        // 原始图片的尺寸
        Integer width1 = 460; // 小图的宽度
        Integer height1 = 256; // 小图的高度

        // 大图片的尺寸
        Integer width2 = 1500; // 大图的宽度
        Integer height2 = 680; // 大图的高度
        // 计算纵横比例因子
        double scaleX = (double) width2 / width1;
        double scaleY = (double) height2 / height1;

        //打印当前时间，yyyy-mm-dd hh:mm:ss
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
       log.info(df.format(new Date()));// new Date()为获取当前系统时间
        log.info(String.valueOf(scaleX));
        log.info(String.valueOf(scaleY));
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(allposinfo);
            JsonNode rowsNode = jsonNode.get("result");
            if(!jsonNode.isArray()){
                for (JsonNode rowNode:rowsNode) {
                    String allPosInfo = rowNode.toString();
                    posSocketHandler.sendMessage(allPosInfo);
//                    String utype = rowNode.get("utype").asText();
                    Integer utype = rowNode.get("utype").asInt();
                    Integer cardid = rowNode.get("card_id").asInt();
                    String personname = rowNode.get("person_name").asText();
                    String licence = rowNode.get("licence").asText();
                    String posx = rowNode.get("x").asText();
                    //将posx转换为大图的坐标
//                    double posx2 = Math.floor(Double.parseDouble(posx) * scaleX);
                    double posx2 = Double.parseDouble(posx) * scaleX;
                    String posy = rowNode.get("y").asText();
                    double posyTrans = 130-Double.parseDouble(posy);
                    //将posy转换为大图的坐标
                    double posy2 = Double.parseDouble(String.valueOf(posyTrans)) * scaleY;
//                    double posy2 = Math.floor(Double.parseDouble(String.valueOf(posyTrans)) * scaleY);
                    String postime = rowNode.get("time").asText();
                    Integer iswork = rowNode.get("on_line").asInt();

                    if(previousIsWorkMap.containsKey(cardid)){
                        if(previousIsWorkMap.get(cardid).equals(iswork)){
                            if(iswork==0){
                                continue;
                            }
                            // 如果新状态为1且与上次保存状态相同, 保存数据
                            log.info("状态为1且与上次保存状态相同, 保存数据");
                            // utype==1,人员，personname为人员名称
                            if(utype == 1){
                                //标签为人员
                                Utype1Entity utype1Entity = new Utype1Entity();
                                Utype1Entity utype1Entity1 = new Utype1Entity();
                                //        pointData.setId(UUID.randomUUID().toString());
                                utype1Entity.setUuid(UUID.randomUUID().toString().replace("-",""));
                                utype1Entity1.setUuid(UUID.randomUUID().toString().replace("-",""));
                                utype1Entity.setCardId(cardid);
                                utype1Entity1.setCardId(cardid);
                                utype1Entity.setPersonName(personname);
                                utype1Entity1.setPersonName(personname);
                                utype1Entity.setPosX(posx2);
                                utype1Entity1.setPosX(Double.parseDouble(posx));
                                utype1Entity.setPosY(posy2);
                                utype1Entity1.setPosY(Double.parseDouble(posy));
                                utype1Entity.setPosTime(Long.parseLong(postime));
                                utype1Entity1.setPosTime(Long.parseLong(postime));
                                utype1Entity.setIsWork(iswork);
                                utype1Entity1.setIsWork(iswork);
                                //存储原始数据
//                                saveToOriginalPos(utype1Entity1);
                                LabelhistoryinfoEntity labelhistoryinfoEntity = convertToLabelhistoryinfoEntity(utype1Entity);
//                                saveToLabelhistoryinfo(labelhistoryinfoEntity);
//                                System.out.println(utype1Entity);
//                                saveToUtype_1(utype1Entity);
                            }else if(utype == 2){
                                //标签为托盘
                                Utype2Entity utype2Entity = new Utype2Entity();
                                //        pointData.setId(UUID.randomUUID().toString());
                                utype2Entity.setUuid(UUID.randomUUID().toString());
                                utype2Entity.setCardId(cardid);
                                utype2Entity.setLicence(licence);
                                utype2Entity.setPosX(Double.parseDouble(posx));
                                utype2Entity.setPosY(Double.parseDouble(posy));
                                utype2Entity.setPosTime(Long.parseLong(postime));
                                utype2Entity.setIsWork(iswork);
                                LabelhistoryinfoEntity labelhistoryinfoEntity = convertToLabelhistoryinfoEntity(utype2Entity);
//                                saveToLabelhistoryinfo(labelhistoryinfoEntity);
//                                System.out.println(utype2Entity);
//                                saveToUtype_2(utype2Entity);
                            }
                        } else {
                            // 如果新状态与上次保存状态不同, 保存数据
                            log.info("新状态与上次保存状态不同, 保存数据");
                            // utype==1,人员，personname为人员名称
                            if(utype == 1){
                                //标签为人员
                                Utype1Entity utype1Entity = new Utype1Entity();
                                Utype1Entity utype1Entity1 = new Utype1Entity();
                                //        pointData.setId(UUID.randomUUID().toString());
                                utype1Entity.setUuid(UUID.randomUUID().toString().replace("-",""));
                                utype1Entity1.setUuid(UUID.randomUUID().toString().replace("-",""));
                                utype1Entity.setCardId(cardid);
                                utype1Entity1.setCardId(cardid);
                                utype1Entity.setPersonName(personname);
                                utype1Entity1.setPersonName(personname);
                                utype1Entity.setPosX(posx2);
                                utype1Entity1.setPosX(Double.parseDouble(posx));
                                utype1Entity.setPosY(posy2);
                                utype1Entity1.setPosY(Double.parseDouble(posy));
                                utype1Entity.setPosTime(Long.parseLong(postime));
                                utype1Entity1.setPosTime(Long.parseLong(postime));
                                utype1Entity.setIsWork(iswork);
                                utype1Entity1.setIsWork(iswork);
                                //存储原始数据
//                                saveToOriginalPos(utype1Entity1);
                                LabelhistoryinfoEntity labelhistoryinfoEntity = convertToLabelhistoryinfoEntity(utype1Entity);
//                                saveToLabelhistoryinfo(labelhistoryinfoEntity);
//                                System.out.println(utype1Entity);
//                                saveToUtype_1(utype1Entity);
                            }else if(utype == 2){
                                //标签为托盘
                                Utype2Entity utype2Entity = new Utype2Entity();
                                //        pointData.setId(UUID.randomUUID().toString());
                                utype2Entity.setUuid(UUID.randomUUID().toString());
                                utype2Entity.setCardId(cardid);
                                utype2Entity.setLicence(licence);
                                utype2Entity.setPosX(Double.parseDouble(posx));
                                utype2Entity.setPosY(Double.parseDouble(posy));
                                utype2Entity.setPosTime(Long.parseLong(postime));
                                utype2Entity.setIsWork(iswork);
                                LabelhistoryinfoEntity labelhistoryinfoEntity = convertToLabelhistoryinfoEntity(utype2Entity);
//                                saveToLabelhistoryinfo(labelhistoryinfoEntity);
//                                System.out.println(utype2Entity);
//                                saveToUtype_2(utype2Entity);
                            }

                            // 更新此cardid的最后保存状态
                            previousIsWorkMap.put(cardid, iswork);
                        }

                    }else {
                        // 如果此cardid之前没有保存状态, 保存数据
                        log.info("此cardid之前没有保存状态, 保存数据");
                        // utype==1,人员，personname为人员名称
                        if(utype == 1){
                            //标签为人员
                            Utype1Entity utype1Entity = new Utype1Entity();
                            Utype1Entity utype1Entity1 = new Utype1Entity();
                            //        pointData.setId(UUID.randomUUID().toString());
                            utype1Entity.setUuid(UUID.randomUUID().toString().replace("-",""));
                            utype1Entity1.setUuid(UUID.randomUUID().toString().replace("-",""));
                            utype1Entity.setCardId(cardid);
                            utype1Entity1.setCardId(cardid);
                            utype1Entity.setPersonName(personname);
                            utype1Entity1.setPersonName(personname);
                            utype1Entity.setPosX(posx2);
                            utype1Entity1.setPosX(Double.parseDouble(posx));
                            utype1Entity.setPosY(posy2);
                            utype1Entity1.setPosY(Double.parseDouble(posy));
                            utype1Entity.setPosTime(Long.parseLong(postime));
                            utype1Entity1.setPosTime(Long.parseLong(postime));
                            utype1Entity.setIsWork(iswork);
                            utype1Entity1.setIsWork(iswork);
                            //存储原始数据
//                            saveToOriginalPos(utype1Entity1);
                            LabelhistoryinfoEntity labelhistoryinfoEntity = convertToLabelhistoryinfoEntity(utype1Entity);
//                            saveToLabelhistoryinfo(labelhistoryinfoEntity);
//                            System.out.println(utype1Entity);
//                            saveToUtype_1(utype1Entity);

                        }else if(utype == 2){
                            //标签为托盘
                            Utype2Entity utype2Entity = new Utype2Entity();
                            //        pointData.setId(UUID.randomUUID().toString());
                            utype2Entity.setUuid(UUID.randomUUID().toString());
                            utype2Entity.setCardId(cardid);
                            utype2Entity.setLicence(licence);
                            utype2Entity.setPosX(Double.parseDouble(posx));
                            utype2Entity.setPosY(Double.parseDouble(posy));
                            utype2Entity.setPosTime(Long.parseLong(postime));
                            utype2Entity.setIsWork(iswork);
                            LabelhistoryinfoEntity labelhistoryinfoEntity = convertToLabelhistoryinfoEntity(utype2Entity);
//                            saveToLabelhistoryinfo(labelhistoryinfoEntity);
//                            System.out.println(utype2Entity);
//                            saveToUtype_2(utype2Entity);
                        }

                        // 更新此cardid的最后保存状态
                        previousIsWorkMap.put(cardid, iswork);
                    }
                }
            }
        } catch (Exception e){
            e.printStackTrace();
        }
        return responseEntity.toString();
    }

    public int saveToOriginalPos(Utype1Entity utype1Entity1) {
        return posinfoDao.saveToOriginalPos(utype1Entity1);
    }

    // 将Utype1Entity转换为LabelhistoryinfoEntity
    public LabelhistoryinfoEntity convertToLabelhistoryinfoEntity(Object source) {
        LabelhistoryinfoEntity labelhistoryinfoEntity = new LabelhistoryinfoEntity();
        labelhistoryinfoEntity.setLabelhistoryNo(UUID.randomUUID().toString().replace("-",""));

        if (source instanceof Utype1Entity){
            Utype1Entity utype1Entity = (Utype1Entity) source;
            labelhistoryinfoEntity.setLabelIdcard(utype1Entity.getCardId());
            labelhistoryinfoEntity.setLabelPosX(utype1Entity.getPosX());
            labelhistoryinfoEntity.setLabelPosY(utype1Entity.getPosY());
            String postime = String.valueOf(utype1Entity.getPosTime());
            long postimeMillis = Long.parseLong(postime); // 将字符串转换为 long 类型的时间戳
// 将 Unix 时间戳转换为 java.sql.Timestamp 对象
            Timestamp timestamp = new Timestamp(postimeMillis);
// 将 java.sql.Timestamp 转换为字符串格式，以便插入数据库
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String formattedDateTime = dateFormat.format(timestamp);
            labelhistoryinfoEntity.setLabelPosTime(formattedDateTime);
            log.info(String.valueOf(labelhistoryinfoEntity));
        } else if(source instanceof Utype2Entity){
            Utype2Entity utype2Entity = (Utype2Entity) source;
            labelhistoryinfoEntity.setLabelIdcard(utype2Entity.getCardId());
            labelhistoryinfoEntity.setLabelPosX(utype2Entity.getPosX());
            labelhistoryinfoEntity.setLabelPosY(utype2Entity.getPosY());
            String postime = String.valueOf(utype2Entity.getPosTime());
            long postimeMillis = Long.parseLong(postime); // 将字符串转换为 long 类型的时间戳
// 将 Unix 时间戳转换为 java.sql.Timestamp 对象
            Timestamp timestamp = new Timestamp(postimeMillis);
// 将 java.sql.Timestamp 转换为字符串格式，以便插入数据库
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String formattedDateTime = dateFormat.format(timestamp);
            labelhistoryinfoEntity.setLabelPosTime(formattedDateTime);
            log.info(String.valueOf(labelhistoryinfoEntity));
        }
        // 设置其他字段...

        return labelhistoryinfoEntity;
    }

    public int saveToUtype_1(Utype1Entity utype1Entity) {

       return posinfoDao.saveToUtype_1(utype1Entity);
    }

    public int saveToLabelhistoryinfo(LabelhistoryinfoEntity labelhistoryinfoEntity) {

       return posinfoDao.saveToLabelhistoryinfo(labelhistoryinfoEntity);
    }
    public int saveToUtype_2(Utype2Entity utype2Entity) {
       return posinfoDao.saveToUtype_2(utype2Entity);
    }

}